<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui 单页面接口增删改查示例</title>
    <link href="static/layui/css/layui.css" rel="stylesheet">
</head>
<body>
<div style="padding:20px;">
    <button class="layui-btn layui-bg-blue" id="addBtn" >新增</button>
    <button type="button"  class="layui-btn" >蓝色按钮</button>
    <br/>
    <br/>
    <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
</div>
<script src="static/layui/layui.js"></script>
<!-- 弹窗表单 -->
<script type="text/html" id="userFormTpl">
    <form class="layui-form" lay-filter="userForm" style="padding:20px;">
        <input type="hidden" name="id">
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="name" placeholder="请输入姓名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
                <input type="text" name="age" placeholder="请输入年龄" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
                <input type="text" name="gender" placeholder="请输入年龄" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitUser">提交</button>
            </div>
        </div>
    </form>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
    layui.use(['table', 'layer', 'form'], function () {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        // 渲染表格
        function renderTable() {
            // 查询接口
            fetch('/api/user/list')
                .then(res => res.json())
                .then(res => {
                    // 假设返回 { code: 0, data: [...] }
                    table.render({
                        elem: '#userTable',
                        cols: [ [
                            {field: 'id', title: 'ID', width: 80},
                            {field: 'name', title: '姓名'},
                            {field: 'age', title: '年龄'},
                            {field: 'gender', title: 'gender'},
                            {title: '操作', toolbar: '#barDemo', width: 180}
                        ] ],
                        data: res.data || [],
                        page: false
                    });
                });
        }
        renderTable();
        // 新增
        document.getElementById('addBtn').onclick = function () {
            openForm('新增用户');
        };
        // 表格工具栏事件
        table.on('tool(userTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                openForm('编辑用户', data);
            } else if (obj.event === 'del') {
                layer.confirm('确定删除吗？', function (index) {
                    // 删除接口
                    fetch('/api/user/' + data.id, {
                        method: 'DELETE'
                    })
                        .then(res => res.json())
                        .then(res => {
                            if (res.code === 200) {
                                layer.msg('删除成功');
                                renderTable();
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                            layer.close(index);
                        });
                });
            }
        });

        // 打开表单弹窗
        function openForm(title, data) {
            layer.open({
                type: 1,
                title: title,
                area: ['600px', '400px'],
                content: document.getElementById('userFormTpl').innerHTML,
                success: function (layero, index) {
                    if (data) {
                        form.val('userForm', data);
                    } else {
                        form.val('userForm', {id: '', name: '', age: ''});
                    }
                    // 提交事件
                    form.on('submit(submitUser)', function (formData) {
                        var field = formData.field;
                        if (field.id) {
                            // 编辑接口
                            fetch('/api/user/' + field.id, {
                                method: 'PUT',
                                headers: {'Content-Type': 'application/json'},
                                body: JSON.stringify({name: field.name, age: field.age, gender: field.gender})
                            })
                                .then(res => res.json())
                                .then(res => {
                                    console.log(res);
                                    if (res.code === 200) {
                                        layer.msg('编辑成功');
                                        renderTable();
                                        layer.close(index);
                                    } else {
                                        layer.msg(res.msg || '编辑失败');
                                    }
                                });
                        } else {
                            // 新增接口
                            fetch('/api/user', {
                                method: 'POST',
                                headers: {'Content-Type': 'application/json'},
                                body: JSON.stringify({name: field.name, age: field.age, gender: field.gender})
                            })
                                .then(res => res.json())
                                .then(res => {
                                    if (res.code === 200) {
                                        layer.msg('新增成功');
                                        renderTable();
                                        layer.close(index);
                                    } else {
                                        layer.msg(res.msg || '新增失败');
                                    }
                                });
                        }
                        return false;
                    });
                }
            });
        }
    });
</script>
</body>
</html>
